from fastapi import APIRouter, Depends, Query
from typing import List
from services.item_service import ItemService
from repositories.item_repository import ItemRepository
from schemas.item import ItemCreate, ItemUpdate, ItemResponse, ItemListResponse

# 依赖注入
from dependencies import get_item_service

# 创建路由器
router = APIRouter(
    prefix="/items",
    tags=["商品管理"],
    responses={404: {"description": "未找到"}}
)

@router.get(
    "",
    response_model=ItemListResponse,
    summary="获取商品列表",
    description="获取所有商品的分页列表"
)
async def get_items(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="返回的记录数限制"),
    service: ItemService = Depends(get_item_service)
):
    """获取商品列表，支持分页"""
    return service.get_items(skip=skip, limit=limit)

@router.get(
    "/{item_id}",
    response_model=ItemResponse,
    summary="获取特定商品",
    description="根据商品ID获取商品详细信息"
)
async def get_item(
    item_id: int,
    service: ItemService = Depends(get_item_service)
):
    """根据ID获取特定商品"""
    return service.get_item_by_id(item_id)

@router.post(
    "",
    response_model=ItemResponse,
    status_code=201,
    summary="创建新商品",
    description="创建一个新的商品"
)
async def create_item(
    item: ItemCreate,
    service: ItemService = Depends(get_item_service)
):
    """创建新商品"""
    return service.create_item(item)

@router.put(
    "/{item_id}",
    response_model=ItemResponse,
    summary="更新商品",
    description="更新指定ID的商品信息"
)
async def update_item(
    item_id: int,
    item_update: ItemUpdate,
    service: ItemService = Depends(get_item_service)
):
    """更新商品信息"""
    return service.update_item(item_id, item_update)

@router.delete(
    "/{item_id}",
    summary="删除商品",
    description="删除指定ID的商品"
)
async def delete_item(
    item_id: int,
    service: ItemService = Depends(get_item_service)
):
    """删除商品"""
    return service.delete_item(item_id)

@router.get(
    "/category/{category}",
    response_model=List[ItemResponse],
    summary="按分类获取商品",
    description="获取指定分类下的所有商品"
)
async def get_items_by_category(
    category: str,
    service: ItemService = Depends(get_item_service)
):
    """根据分类获取商品"""
    return service.get_items_by_category(category)

@router.post(
    "/demo/create-and-read",
    response_model=dict,
    summary="调用链Demo - 创建并查询",
    description="演示完整的调用链：创建商品然后立即查询"
)
async def demo_create_and_read(
    service: ItemService = Depends(get_item_service)
):
    """Demo: 展示Router→Service→Repository→Database调用链"""
    
    # 🌐 Router层: 构造Demo数据 (模拟接收JSON)
    demo_item = ItemCreate(
        name="Demo商品",
        description="调用链演示商品",
        price=99.99,
        category="Demo分类"
    )
    
    # 调用链: Router → Service → Repository → Database
    created_item = service.create_item(demo_item)
    
    # 调用链: Router → Service → Repository → Database (查询)
    read_item = service.get_item_by_id(created_item.id)
    
    return {
        "message": "调用链Demo完成",
        "调用链路": [
            "🌐 Router层: 接收JSON → ItemCreate(Schema)",
            "🔧 Service层: Schema→Dict→Model转换 + 业务逻辑",
            "💾 Repository层: 只处理Models，保存到内存数据库", 
            "🗄️ Database: 持久化Models数据"
        ],
        "created_item": created_item.dict(),
        "read_item": read_item.dict(),
        "验证": "创建和查询的数据一致" if created_item.id == read_item.id else "数据不一致"
    }

@router.get(
    "/demo/service-layer",
    response_model=dict,
    summary="Service层Demo",
    description="演示Service层调用Repository层的完整流程"
)
async def demo_service_layer(
    service: ItemService = Depends(get_item_service)
):
    """Demo: 展示Service层→Repository层调用链"""
    return service.demo_crud_operations()

@router.get(
    "/demo/repository-layer", 
    response_model=dict,
    summary="Repository层Demo",
    description="演示Repository层直接操作Models"
)
async def demo_repository_layer(
    service: ItemService = Depends(get_item_service)
):
    """Demo: 展示Repository层只处理Models"""
    # 通过Service获取Repository实例
    return service.repository.demo_repository_operations() 